package com.jlnk.stockdemo.viewmodel;

import android.util.Log;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jlnk.stockdemo.bean.FutureListRequest;
import com.jlnk.stockdemo.bean.FutureListResponse;
import com.jlnk.stockdemo.callback.ResponseCallback;
import com.jlnk.stockdemo.utils.NetworkUtils;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.List;

public class FutureViewModel extends ViewModel {
    private static final String TAG = "FutureViewModel";
    private MutableLiveData<List<FutureListResponse.Data.Future>> futureListLiveData;

    public FutureViewModel() {
        futureListLiveData = new MutableLiveData<>();
    }

    public LiveData<List<FutureListResponse.Data.Future>> getFutureListLiveData() {
        return futureListLiveData;
    }

    // 获取期货列表
    public void fetchFutureList() {
        FutureListRequest futureListRequest = new FutureListRequest();
        FutureListRequest.Params params = new FutureListRequest.Params();
        params.setExchange("DCE");
        futureListRequest.setParams(params);
        NetworkUtils.sendPostRequest(futureListRequest, new ResponseCallback() {
            @Override
            public void onResponse(String response) {
                // 在这里处理响应数据
                Gson gson = new Gson();
                Type type = new TypeToken<FutureListResponse>(){}.getType();
                FutureListResponse futureListResponse = gson.fromJson(response, type);
                if (futureListResponse != null) {
                    // 在这里处理解析后的数据
                    List<FutureListResponse.Data.Future> futureList = futureListResponse.getData().getFutureList();
                    futureListLiveData.postValue(futureList);
                }
            }

            @Override
            public void onPermissionError(String msg) {
                Log.d(TAG, "onPermissionError: " + msg);
            }

            @Override
            public void onInternalError(String msg) {
                Log.d(TAG, "onInternalError: " + msg);
            }

            @Override
            public void onFailure(IOException e) {
                Log.d(TAG, "onFailure: " + e.getMessage());
            }
        });
    }
}
